package cn.lsnu.modules.watch.controller;

import cn.lsnu.common.interfacetools.interfacecontroller.BaseController;
import cn.lsnu.modules.watch.entity.WatchMaintEntity;
import cn.lsnu.modules.watch.service.WatchMaintService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping({"/app/watchmaint"})
public class WatchMaintController extends BaseController {

    @Autowired
    private WatchMaintService watchMaintService;
    @RequestMapping("/save")
    public
    @ResponseBody
    WatchMaintEntity save(WatchMaintEntity entity, HttpServletRequest request)throws Exception{
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        String path = request.getSession().getServletContext().getRealPath("/upload/image");
        //图片上传成功后，将图片的地址写到数据库
        File fileUrl=new File(path);
        //如果当前项目里不存在images文件夹，就创建
        if(!fileUrl.exists()){
            fileUrl.mkdir();
        }
        String filePaths= "";
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> mpfile : fileMap.entrySet()) {
            MultipartFile mf = mpfile.getValue();
            // 获得原始文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            //获取图片的原始图片的后缀名
            String ext = FilenameUtils.getExtension(mf.getOriginalFilename());
            ext = ext.substring(0,ext.indexOf("?"));
            File targetFile = new File(path,"/"+res+"."+ext);
            mf.transferTo(targetFile);
            filePaths =filePaths + "/upload/image/"+res+"."+ext+"-";
        }
        entity.setMaintImgUrl(filePaths);
        watchMaintService.save(entity);
        entity = entity == null?new WatchMaintEntity():entity;
        entity.setCode("200");
        entity.setMsg("提交成功");
        return  entity;
    }

}
